package mytest;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;

import java.util.Date;

public class ClientHandler extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        try {
            Channel channel = ctx.channel(); // 获取channel的引用
            ByteBuf buf = Unpooled.copiedBuffer("your data", CharsetUtil.UTF_8); //1
            ChannelFuture cf = channel.writeAndFlush(buf); //2
            cf.addListener(new ChannelFutureListener() { //3
                @Override
                public void operationComplete(ChannelFuture future) {
                    if (future.isSuccess()) { //4
                        System.out.println("Write successful");
                    } else {
                        System.err.println("Write error"); //5
                        future.cause().printStackTrace();
                    }
                }
            });
        } finally {
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
